<template>
  <div>
    <hd-tab :tabs="tabs"></hd-tab>

    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span v-if="this.id">编辑商品</span>
        <span v-else>添加商品</span>
      </div>
      <el-form :model="form" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="form.name"></el-input>
          <hd-error name="name"></hd-error>
        </el-form-item>

        <el-form-item label="分类选择">
          <el-select v-model="form.category_id" placeholder="请选择">
            <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
          <hd-error name="category"></hd-error>
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="form.unit" placeholder="请选择">
            <el-option
                v-for="item in units"
                :key="item"
                :label="item"
                :value="item">
            </el-option>
          </el-select>
          <hd-error name="category"></hd-error>
        </el-form-item>
        <el-form-item label="商品单价">
          <el-input-number v-model="form.perprice"
                           :precision="2"
                           :step="0.5"
                           placeholder="请填写价格">
          </el-input-number>
          <hd-error name="perprice"></hd-error>
        </el-form-item>
        <el-form-item label="图片">
          <hd-image v-model="form.image"></hd-image>
          <hd-error name="image"></hd-error>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description"
                    placeholder="请填写描述"
                    rows="5"
                    type="textarea"></el-input>
          <hd-error name="image"></hd-error>
        </el-form-item>
      </el-form>

    </el-card>
    <el-button class="mt-3" type="primary" @click="onSubmit">提交</el-button>
  </div>
</template>

<script>
const units = ['件', '份', '瓶', '锅', '两', '斤', '盒']
import tabs from './tabs.js'

export default {
  route: false,
  props: ['id'],
  data() {
    return {
      form: {},
      units,
      categories: [],
      tabs
    }
  },
  async created() {
    if (this.id) {
      this.form = await this.axios.get(`admin/product/${this.id}`)
    }
    this.categories = await this.axios.get(`admin/category`)
  },
  methods: {
    async load() {
      if (this.id) {
        this.form = await this.axios.get(`admin/product/${this.id}`)
      }
    },
    async onSubmit() {
      const url = this.id ? `admin/product/${this.id}` : `admin/product`
      await this.axios[this.id ? "put" : "post"](url, this.form)
      this.$router.push({name: 'admin.product.index'})
    }
  }

}
</script>

<style scoped>

</style>